import 'dart:convert';

import 'package:kkhousekeep/net/base_connect.dart';
import 'package:kkhousekeep/net/respnse_code.dart';
import 'package:kkhousekeep/tools/dialog_util.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../models/home_room_entity.dart';
import '../models/house_authentication_list_entity.dart';
import '../models/me_room_new_msg_entity.dart';
import '../models/room_token_entity.dart';
import '../tools/shared_preferences.dart';
import 'api.dart';

class MeConnect extends BaseConnect {
  Future<bool> checkRoomNewMsg() async {
    var response = await post(Api.checkRoomNewMsg, {});
    if (response.body == null) {
      DialogUtil.showNetworkError();
      return Future.value(false);
    }
    MeRoomNewMsgEntity entity = MeRoomNewMsgEntity.fromJson(response.body);

    if (entity.code == ResponseCode.success) {
      return Future.value(entity.obj.exist);
    }
    return Future.value(false);
  }

  Future<HomeRoomObjList> getRoomInfo() async {
    var defaultRoom = HomeRoomObjList().copyWith(
        roomId: -1,
        cityName: '',
        communityName: '',
        buildingName: '',
        unitName: '',
        roomName: '');
    var sp = await SharedPreferences.getInstance();
    if (sp.containsKey(SpKey.roomInfo)) {
      HomeRoomObjList roomObjList = HomeRoomObjList.fromJson(
          jsonDecode(sp.getString(SpKey.roomInfo) ?? ''));
      return Future.value(roomObjList);
    }
    List<HomeRoomObjList> rooms = await getRooms();
    if (rooms.isNotEmpty) {
      var room = rooms[0];
      sp.setString(SpKey.roomInfo, jsonEncode(room.toJson()));
      return Future.value(room);
    }
    return Future.value(defaultRoom);
  }

  Future<List<HomeRoomObjList>> getRooms() async {
    var response = await post(Api.getRoomList, {});
    if (response.body == null) {
      DialogUtil.showNetworkError();
      return Future.value([]);
    }
    HomeRoomEntity entity = HomeRoomEntity.fromJson(response.body);
    if (ResponseCode.success == entity.code) {
      return Future.value(entity.obj.list);
    }
    return Future.value([]);
  }

  Future<RoomTokenEntity?> switchHouse({
    required int roomId,
  }) async {
    var response = await post(Api.changeHouse, {
      'roomID': roomId,
    });
    if (response.body == null) {
      DialogUtil.showNetworkError();
      return Future.value();
    }
    RoomTokenEntity entity = RoomTokenEntity.fromJson(response.body);
    return Future.value(entity);
  }

  Future<List<HouseAuthenticationListObjList>>
      getHouseAuthNotificationList() async {
    var response = await post(Api.getRoomCheckList, {});
    if (response.body == null) {
      DialogUtil.showNetworkError();
      return Future.value([]);
    }
    HouseAuthenticationListEntity entity =
        HouseAuthenticationListEntity.fromJson(response.body);
    return Future.value(entity.obj.list);
  }
}
